/**
 * Henry Hu
 */
package com.atsmart.app.service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.activity.LoginActivity;
import com.atsmart.app.model.PositionAttributeInfo;
import com.atsmart.app.model.PositionSwitchInfo;
import com.atsmart.app.model.PositonTimeListInfo;
import com.atsmart.app.model.TimeSheetsInfo;

import com.atsmart.app.sql.PositionSqlHelper;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
//import com.atsmart.log.UserLog;

/**
 * @author Henry Hu
 * 
 */
public class CheckingService extends Service {

	public Double lon;
	public Double lat;
	public Intent it;
	private int dur = 0;;
	private PositionSqlHelper psql = null;
	private  AlarmManager am = null;
	private  PendingIntent pi = null;
	private PowerManager.WakeLock wakeLock = null;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		acquireWakeLock();
		relesseWakeLock();
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,CheckingService.class.getName());
		super.onCreate();

	}
	@Override
	public void onStart(Intent intent, int startId) {

	}

	
	private void relesseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	private void acquireWakeLock() {
		if (null == wakeLock) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
					| PowerManager.ON_AFTER_RELEASE, "");
		}
		if (null != wakeLock) {
			wakeLock.acquire();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

	}

	@Override
	public boolean stopService(Intent name) {
		return super.stopService(name);
	}
	
	private String is = "";
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			Bundle bundle = intent.getExtras();
			if(bundle != null){
				is = bundle.getString("isfromlogin");
//				UserLog.getInstance().writelocal("is: = " + is + " , time: = " + StringUtil.getCurrentTime());
			}
			new Thread() {
				public void run() {
					setTimerStart(is);
				}
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
//			UserLog.getInstance().writeException(e);
		}
		//onStartCommand有4种返回值：
		//START_STICKY：如果service进程被kill掉，保留service的状态为开始状态，但不保留递送的intent对象。随后系统会尝试重新创建service，由于服务状态为开始状态，所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service，那么参数Intent将为null。
		//START_NOT_STICKY：“非粘性的”。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统不会自动重启该服务。
		//START_REDELIVER_INTENT：重传Intent。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统会自动重启该服务，并将Intent的值传入。
		//START_STICKY_COMPATIBILITY：START_STICKY的兼容版本，但不保证服务被kill后一定能重启
		//START_REDELIVER_INTENT 重传Intent。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统会自动重启该服务，并将Intent的值传入
//		return START_REDELIVER_INTENT;
		flags = START_REDELIVER_INTENT;
		 return super.onStartCommand(intent, flags, startId);

	}

	private void setTimerStart(String is) {
		
		try {
			 Log.e("CheckingService", "setTimerStart");
			psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
	 
			if (BizApp.getInstance().keeping) {
				getSheet();
			}
			
			if (am == null) {
				if(!StringUtil.isEmptyOrNull(is) && is.equals("1")){
					am = (AlarmManager) getSystemService(ALARM_SERVICE);
					pi = PendingIntent.getService(getApplicationContext(), 1023, new Intent(getApplicationContext(), infoService.class), 0);
					long now = SystemClock.elapsedRealtime();
					am.setRepeating(AlarmManager.RTC_WAKEUP, now, 60 * 1000, pi);
				}else{
					if (!StringUtil.isEmptyOrNull(PrefsUtils.getRegisteredPhone())) {
						am = (AlarmManager) getSystemService(ALARM_SERVICE);
						pi = PendingIntent.getService(getApplicationContext(), 1023, new Intent(getApplicationContext(), infoService.class), 0);
						long now = SystemClock.elapsedRealtime();
						am.setRepeating(AlarmManager.RTC_WAKEUP, now, 60 * 1000, pi);
					} else {
						this.stopSelf();
						this.startActivity(new Intent(this, LoginActivity.class));
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	

	private void getSheet() {
		PositonTimeListInfo o1 = null;
		try {
			o1 = ServiceHelper.getInstance().postData(
					ServiceHost.positiontimeURL(), "",
					PositonTimeListInfo.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (o1 != null) {

				StringBuffer sbf = new StringBuffer();
				if (o1.getPosition() != null) {
					for (PositionSwitchInfo sinfo : o1.getPosition()) {
						sbf.append(String.valueOf(sinfo.getWeek() + ","
								+ sinfo.getSwit()));
						for (TimeSheetsInfo tinfo : o1.getTime()) {
							if (sinfo.getWeek() == tinfo.getWeek()) {
								sbf.append(","
										+ String.valueOf(tinfo.getBeginHour()
												+ "," + tinfo.getBeginMin())
										+ ",");
								sbf.append(String.valueOf(tinfo.getEndHour()
										+ "," + tinfo.getEndMin()));
							}
						}
						sbf.append(";");
					}

				}
				PositionAttributeInfo pinfo = psql.getAttribute();
				if (pinfo == null) {
					pinfo = new PositionAttributeInfo();
					pinfo.setDur(o1.getRate());
					pinfo.setSheet(sbf.toString());
					pinfo.setOpen(1);
					psql.addAttribute(pinfo);
					PositionAttributeInfo attributeInfo = psql.getAttribute();
				} else {
					dur = o1.getRate();
					if (pinfo.getDur() != dur) {
						psql.updateAttribute(1);
					} else {
						psql.updateAttribute(0);
					}

					psql.updateSheetAndRate(sbf.toString(), o1.getRate());
				}
			}

		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
			e.printStackTrace();
		}
	}
	

	public void saveToSDCard(String filename, String content) throws Exception {
		// Environment.getExternalStorageDirectory()��ʾ�ҵ�sdcarfĿ¼
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		FileOutputStream outStream = new FileOutputStream(file, true);
		outStream.write(content.getBytes());
		outStream.close();
	}

}
